import { wxLogin, setAPIToken, getSeverUserInfo } from '../../api/eapi';

let timeout='';

Page({
  data: {
    scanCode: false
  },
  onTabItemTap(item) {
   this.setData({
     scanCode:true
   })
    this.openQR();
  },
  onLoad(options) {
    if(options.navigator2){
      wxLogin("登录").then(res => {
      wx.navigateTo({
        url: `../catalog/product/index?product=${options.navigator2}`,
      })
      }).catch(err => {
        wx.navigateBack()
      })
    }else if(options.navigator1){
      wxLogin("登录").then(res => {
      wx.navigateTo({
        url: `../cms/article/index?product=${options.navigator1}`,
      })
      }).catch(err => {
        wx.navigateBack()
      })
    }else{ 
    wxLogin("登录").then(res => {
      wx.switchTab({
        url: '../catalog/home/index',
      })
    }).catch(err => {
      wx.navigateBack()
    })
    }
  },
  openQR() {
    let _this = this;
    wx.scanCode({
      success: function (res) {
        let exr = /letsdrink-mprog.aosaiban.com/;
        if (res.result.match(exr)) {
          console.log(res)
          wx.redirectTo({
            url: '../catalog/product/index?code=' + res.result
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '未能识别该二维码',
            showCancel: true,
            cancelText: '返回首页',
            confirmText: '重新扫描',
            success: function (res) {
              
              if (res.confirm) {
                _this.openQR()
              } else if (res.cancel) {
                wx.switchTab({
                  url: '../catalog/home/index',
                })
              }
            },
            fail: function (res) {
              wx.switchTab({
                url: '../catalog/home/index',
              })
            },
            complete:function(res){
              _this.setData({
                scanCode: false
              })
             
            }
          })
        }
      },
      fail: function (e) {
        if (e.errMsg == 'scanCode:fail cancel') {
          wx.switchTab({
            url: '../catalog/home/index'
          })
        } else {
          wx.showToast({
            title: `错误${e.errMsg}`,
            icon: 'none',
            mask: true
          })
        }
      }
    })
  },
  onShow: function () {
  
    if (this.data.scanCode){ 
    wx.showLoading({
      title: 'loading'
    });
    timeout=setTimeout(function(){
      wx.hideLoading();
      wx.switchTab({
        url: '../catalog/home/index'
      })
    },500)

    }else{
      wx.showLoading({
        title: 'loading'
      });
    }
    
  },
  onHide: function () {
    wx.hideLoading();
    clearTimeout(timeout);
    
  }
})
